package com.cls.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cls.yygh.hosp.repository.DepartmentRepository;
import com.cls.yygh.hosp.service.DepartmentService;
import com.cls.yygh.model.hosp.Department;
import com.cls.yygh.vo.hosp.DepartmentQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.Map;

/**
 * @program: yygh
 * @description:
 * @author: LH
 * @create: 2021-11-10 11:37
 **/
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    DepartmentRepository departmentRepository;


    @Override
    public void save(Map<String, Object> paramMap) {
        String jsonString = JSONObject.toJSONString(paramMap);

        Department department = JSONObject.parseObject(jsonString, Department.class);

        String hoscode = department.getHoscode();

        String depcode = department.getDepcode();

        Department departmentByDepcode = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode,depcode);

        if (departmentByDepcode != null){
            department.setIsDeleted(0);
            department.setUpdateTime(new Date());
            department.setCreateTime(departmentByDepcode.getCreateTime());
            departmentRepository.save(department);
        }else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    @Override
    public Page<Department> selectPage(int page, int limit, DepartmentQueryVo departmentQueryVo) {

        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");

        Pageable pageable = PageRequest.of(page-1,limit,sort);

        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo,department);
        department.setIsDeleted(0);

        //创建匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()  //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true);  //改变默认大小写忽略方式：忽略大小写

        //创建实例
        Example<Department> example = Example.of(department,matcher);

        Page<Department> pages = departmentRepository.findAll(example,pageable);

        return pages;
    }

    @Override
    public void remove(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (null!=department){
            departmentRepository.deleteById(department.getId());
        }
    }

}
